package com.wslds.base.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;

import org.apache.struts2.ServletActionContext;

import com.wslds.base.dao.BaseDaoImpl;
import com.wslds.bean.Tag;
import com.wslds.bean.ext.TaginstExt;

public class SessionUtil {
	
	private static ServletContext servletContext;
	
	public static String getContextPath(){
		return (String)ServletActionContext.getServletContext().getAttribute("contextPath");
	}
	
	public static ServletContext getServletContext(){
		return servletContext;
	}

	public static void setServletContext(ServletContext _servletContext) {
		servletContext = _servletContext;
	}
	
	public static Object getGlobe( String key ){
		return servletContext.getAttribute(key);
	}
	
	public static void refreshTag(){
		
		TaginstExt tagParam = new TaginstExt();
		List<TaginstExt> taginstExt = ((BaseDaoImpl)SpringAppContextUtil.getApplicationContext().getBean("iDao")).findExt("tag_select_ext", tagParam);
		Map<Long,List<TaginstExt>> taginstMap = new HashMap<Long,List<TaginstExt>>();
		for( TaginstExt taginst: taginstExt ){
			if( taginstMap.containsKey(taginst.getArtId()) ){
				List<TaginstExt> list = taginstMap.get(taginst.getArtId());
				list.add(taginst);
			}else{
				List<TaginstExt> list = new ArrayList<TaginstExt>();
				list.add(taginst);
				taginstMap.put(taginst.getArtId(), list);
			}
		}
		SessionUtil.getServletContext().setAttribute(BlogCons.APPLICATION.TAG, taginstMap);
		
		
		//把标签放到全局
		List<Tag> tagList = ((BaseDaoImpl)SpringAppContextUtil.getApplicationContext().getBean("iDao")).find("tag", null);
		Map<Long,String> tagMap = new HashMap<Long,String>();
		for( Tag tag: tagList ){
			tagMap.put(tag.getId(), tag.getName());
		}
		SessionUtil.getServletContext().setAttribute(BlogCons.APPLICATION.TAG, tagMap);
		
	}
	
	public static void refreshSidebar(){
		BaseDaoImpl dao = (BaseDaoImpl)SpringAppContextUtil.getApplicationContext().getBean("iDao");
		//侧边栏全局数据
		SessionUtil.getServletContext().setAttribute("typeList", dao.findExt("type_select_sidebar", null));
		SessionUtil.getServletContext().setAttribute("dateList", dao.findExt("date_select_sidebar", null));
	}


}
